package com.epalmpay.controller.apiweixin;


import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.epalmpay.commom.BaseController;
import com.epalmpay.dto.member.MemberOutDTO;
import com.epalmpay.service.group.IGroupService;
import com.epalmpay.service.member.IMemberService;
import com.epalmpay.service.weixin.ITokenService;
import com.epalmpay.service.weixin.IWxApiService;
import com.epalmpay.service.weixin.IWxBaseService;
import com.epalmpay.service.weixin.impl.WxService;
import com.epalmpay.util.PageData;
import com.epalmpay.util.Token;
import com.epalmpay.util.Tools;

import me.chanjar.weixin.common.api.WxConsts;
import me.chanjar.weixin.mp.bean.result.WxMpOAuth2AccessToken;

/**
 * 
 * 类名称：WechatController.java 类描述： 微信公众号开发网页授权
 * 
 * @author zsj 创建时间：2017年5月18日
 */
@Controller
@RequestMapping(value = "/api/menu")
public class WechatMenuController extends BaseController {

	@Autowired
	protected WxService wxService;

	@Autowired
	protected IWxBaseService wxBaseService;
	@Resource
	private IMemberService memberService;
	@Resource
	private IGroupService groupService;

	@Resource
	private IWxApiService wxApiService;

	@Autowired
	private ITokenService tokenService;
    
    @Value("${WX_Key}")
    private String wXKey;
	    

    /**
     * 
     * @param request
     * @param response
     * @param groupId
     * @throws Exception
     */
	@RequestMapping(value = "personal", method = { RequestMethod.GET, RequestMethod.POST })
	public void wechatOpenId(HttpServletRequest request, HttpServletResponse response,String groupId,String name) throws Exception {
		logBefore(logger, "--------------------------个人中心----------获取微信openId第1步开始------------------------------------");
		if(Tools.isEmpty(name)||Tools.isEmpty(groupId)){
			return;
		}



		wxService.setWxMpConfigStorage(wxBaseService.getTokenByGroupId(Long.valueOf(groupId)));
		String referer = request.getHeader("Referer");
		String state = "";
		String url = HOME_URL + "/api/menu/wxPersonalCallback";
		if (referer == null) {
			// 首页 html       
			referer=String.format("%s/"+groupId+"/"+name+".html",ROOT_HOME_URL);
		}
		state = java.net.URLEncoder.encode(referer, "utf-8");
		wxService.setWxMpConfigStorage(wxBaseService.getTokenByGroupId(Long.valueOf(groupId)));
		String href = wxService.oauth2buildAuthorizationUrl(url+"?groupId="+groupId, WxConsts.OAUTH2_SCOPE_BASE, state);
		logBefore(logger, "------------------------------------获取微信openId第1步结束-----------------------------------");
		response.sendRedirect(href);
	}

	@RequestMapping(value = "wxPersonalCallback", method = { RequestMethod.GET, RequestMethod.POST })
	public String wxCallbackCode(HttpServletRequest request, HttpServletResponse response) throws Exception {
		logBefore(logger, "------------------------------------获取微信openId第2步开始------------------------------------");
		PageData pd = new PageData();
		pd = this.getPageData();
		
		logBefore(logger, "------------------------------------接收的参数------------------------------------"+pd);
		
		
		String groupId = pd.getString("groupId");
		String code = pd.getString("code");
		String state = pd.getString("state");
		wxService.setWxMpConfigStorage(wxBaseService.getTokenByGroupId(Long.parseLong(groupId)));
		WxMpOAuth2AccessToken wxMpOAuth2AccessToken = this.wxService.oauth2getAccessToken(code);
		String openId = wxMpOAuth2AccessToken.getOpenId();
		if (Tools.isEmpty(openId)) {
			response.sendRedirect(state);
		} else {
			MemberOutDTO member = memberService.queryAmountOpenId(openId, groupId);
			// 查询是否开通钱包 即查询大商户是否开通分销商管理模块 memberId正式环境做ace加密处理
			Boolean flag = groupService.selectGroupModel(Long.parseLong(groupId));
			// 会员是否签到
			Integer signState = wxApiService.querytodaymemberSign(member.getId(), Long.parseLong(groupId));
			Long memberId = member.getId();
			Token token = tokenService.getTokenInfo(memberId + "");
			StringBuffer bf=new StringBuffer();
				if (flag) {
					if (Tools.isEmpty(member.getVirtualCard())) {
						if(state.contains("?")){
						     bf.append(state)
							.append("&memberId="+memberId)
							.append("&groupId="+groupId)
							.append("&openedStatus="+1)
							.append("&loginStatus="+0)
							.append("&signState="+signState)
							.append("&token="+token.getValue())
							.append("&redPacket=0")
									 .append("&isreg="+0);
						}else{
							 bf.append(state)
							.append("?memberId="+memberId)
							.append("&groupId="+groupId)
							.append("&openedStatus="+1)
							.append("&loginStatus="+0)
							.append("&signState="+signState)
							.append("&token="+token.getValue())
							.append("&redPacket=0")
							 .append("&isreg="+0);
						}
					} else {
						// 显示余额
						if(state.contains("?")){
							     bf.append(state)
								.append("&memberId="+memberId)
								.append("&groupId="+groupId)
								.append("&openedStatus="+1)
								.append("&loginStatus="+1)
								.append("&signState="+signState)
								.append("&curBal="+member.getCurBal())
								.append("&token="+token.getValue())
								.append("&redPacket="+member.getRedPacket())
								 .append("&isreg="+1);
							
						}else{
							 bf.append(state)
							.append("?memberId="+memberId)
							.append("&groupId="+groupId)
							.append("&openedStatus="+1)
							.append("&loginStatus="+1)
							.append("&signState="+signState)
							.append("&curBal="+member.getCurBal())
							.append("&token="+token.getValue())
							.append("&redPacket="+member.getRedPacket())
							 .append("&isreg="+1);
						}
					}
				} else {
					if(state.contains("?")){
						     bf.append(state)
							.append("&memberId="+memberId)
							.append("&groupId="+groupId)
							.append("&openedStatus="+0)
							.append("&signState="+signState)
							.append("&token="+token.getValue())
							.append("&redPacket=0")
							 .append("&isreg="+0);
						}else{
							 bf.append(state)
							.append("?memberId="+memberId)
							.append("&groupId="+groupId)
							.append("&openedStatus="+0)
							.append("&signState="+signState)
							.append("&token="+token.getValue())
							.append("&redPacket=0")
							 .append("&isreg="+0);
					}
				}
				bf.append("&random=").append(Tools.getRandomNumABC(6));
			response.sendRedirect(bf.toString());
		}
		logBefore(logger, "------------------------------------获取微信openId第2步结束------------------------------------");
		return null;
	}
	
	
	
	
	
	 /**
     * @param request
     * @param response
     * @param groupId
     * @throws Exception
     */
	@RequestMapping(value = "test", method = { RequestMethod.GET, RequestMethod.POST })
	public void test(HttpServletRequest request, HttpServletResponse response,String groupId,String name) throws Exception {
		logBefore(logger, "--------------------------测试外部链接------------------------------------");
		response.sendRedirect("http://xc.earsgo.cn/oauth?appid=wxf3b897cf460c8b7d&state=1");
	}
	
	

}
